package com.ly.system.controller;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ly.config.handler.BusinessException;
import com.ly.config.response.Result;
import com.ly.config.response.ResultCode;
import com.ly.system.entity.TbUser;
import com.ly.system.service.TbDepartmentService;
import com.ly.system.service.TbUserService;
import com.ly.system.vo.TbDepartmentVO;
import com.ly.system.vo.TbUserVO;
import com.ly.system.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/User")
@Api(value = "系统用户模块",tags = "系统用户接口")
@CrossOrigin  //用于解决跨域问题
public class TbUserController {

    @Resource
    RedisTemplate<String,Object> redisTemplate;
    // @Autowired
    @Resource
    private TbUserService tbUserService;

    @Resource
    private TbDepartmentService tbDepartmentService;

    @PostMapping("/findUser")
    @ApiOperation(value = "用户列表", notes = "查询用户信息")
    public Result findUser(
            @RequestParam(required = true, defaultValue = "1") Integer current,
            @RequestParam(required = true, defaultValue = "6") Integer size,
            @RequestBody(required = false) TbUserVO tbUserVO
    ) {
        //对用户进行分页，泛型中注入的就是用户实体类
        Page<TbUser> page = new Page<>(current, size);
        QueryWrapper<TbUser> wrapper = getWrapper(tbUserVO);
        IPage<TbUser> tbUserPage = tbUserService.findUserPage(page, wrapper);
        long total = tbUserPage.getTotal();
        List<TbUser> records = tbUserPage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }

    /**
     * 封装查询条件
     *
     * @param tbUserVO
     * @return
     */
    private QueryWrapper<TbUser> getWrapper(TbUserVO tbUserVO) {
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("deleted", 0);
        if (tbUserVO != null) {
            System.out.println(11);
            System.out.println(tbUserVO.getDepartmentId());
            if (!StringUtils.isEmpty(tbUserVO.getDepartmentId())) {
                queryWrapper.eq("department_id", tbUserVO.getDepartmentId());
                System.out.println(222);
            }
            if (!StringUtils.isEmpty(tbUserVO.getUsername())) {
                queryWrapper.like("username", tbUserVO.getUsername());
            }
            if (!StringUtils.isEmpty(tbUserVO.getEmail())) {
                queryWrapper.eq("email", tbUserVO.getEmail());
            }
            if (!StringUtils.isEmpty(tbUserVO.getSex())) {
                queryWrapper.eq("sex", tbUserVO.getSex());
            }
            if (!StringUtils.isEmpty(tbUserVO.getNickname())) {
                queryWrapper.like("nickname", tbUserVO.getNickname());
            }
        } else {
            System.out.println(333);
        }
        return queryWrapper;
    }

    @ApiOperation(value = "查询部门及人数", notes = "从部门表中分组查询用户人数")
    @PostMapping("/userList")

    public Result findDeptAndCount(Integer id) {
        TbUser byId = tbUserService.getById(id);

        return Result.ok().data("User", byId);
    }

    @PostMapping("/addUser")
    @ApiOperation(value = "用户列表", notes = "新增用户信息")
    public Result addUser(@RequestBody TbUser User) {
        tbUserService.addUser(User);

        return Result.ok().data("list", "完成");
    }

    @PostMapping("/updUser")
    @ApiOperation(value = "用户列表", notes = "修改用户信息")
    public Result updUser(@RequestBody TbUser User) {
        tbUserService.updUser(User);

        return Result.ok().data("list", "完成");
    }

    @DeleteMapping("/updateUser")
    @ApiOperation(value = "用户列表", notes = "新增用户信息")
    public Result updateUser(Integer id) {
        System.out.println(id);
        tbUserService.removeById(id);
        return Result.ok().data("list", "完成");

    }

    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, @RequestBody(required = false) TbUserVO userVO) throws IOException {
        QueryWrapper<TbUser> wrapper = getWrapper(userVO);
        List<TbUser> users = tbUserService.list(wrapper);
        tbUserService.exportUserExcel(response, users);
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "用户列表", notes = "新增用户信息")
    public void updateStatus(Integer status, Integer id) {

        tbUserService.updatestatus(status, id);


    }

    public TbDepartmentService getTbDepartmentService() {
        return tbDepartmentService;
    }

//    @PostMapping("yz")
//    public Result yz(){
//
//    }
   @PostMapping("dx")
    public Result dx(String phone) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FzgBkCXqNuszTPgRxid", "Htc6qZbTVsolDIRrbhbSRUHYdWh4ET");
        IAcsClient client = new DefaultAcsClient(profile);
       String value = String.valueOf((int)((Math.random()*9+1)*1000));


       CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "疫情管理系统");
        request.putQueryParameter("TemplateCode", "SMS_205825706");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+value+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

       return Result.ok().data("yzm",value,"phone",phone);
    }

    @PostMapping("login")
    public Result login(String name,String pwd){

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",name);
        System.out.println(name);
        TbUser user = tbUserService.getOne(queryWrapper);
        if(user==null){
            return Result.error().data("data",false);
        }
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(pwd, user.getPassword());
        if(!matches){
            return Result.error().data("data",false);
        }
        return Result.ok().data("data",true);


    }
}




